package com.yunxin.core.wechat.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.core.admin.domain.AdminTeam;
import com.yunxin.core.admin.domain.AdminUser;
import com.yunxin.core.admin.domain.AdminUserTeamShip;
import com.yunxin.core.admin.service.AdminTeamService;
import com.yunxin.core.admin.service.AdminUserService;
import com.yunxin.core.admin.service.AdminUserTeamShipService;
import com.yunxin.core.customer.domain.CustomerInfo;
import com.yunxin.core.customer.domain.CustomerInfoDetail;
import com.yunxin.core.customer.dto.CustomerWechatPageDto;
import com.yunxin.core.customer.dto.TeamPageDto;
import com.yunxin.core.customer.service.CustomerInfoDetailService;
import com.yunxin.core.customer.service.CustomerInfoService;
import com.yunxin.core.customer.vo.CustomerCommonVo;
import com.yunxin.core.customer.vo.CustomerWechatInfoVo;
import com.yunxin.core.domain.model.team.Team;
import com.yunxin.core.wechat.domain.*;
import com.yunxin.core.wechat.dto.GetWechatCustomersDto;
import com.yunxin.core.wechat.service.*;
import com.yunxin.core.wechat.mapper.WechatFollowCustomerMapper;
import com.yunxin.core.wechat.vo.WechatFollowCustomerListVo;
import com.yunxin.core.wechat.vo.WechatGroupTagVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【wechat_follow_customer(企业用户关联客户信息)】的数据库操作Service实现
 * @createDate 2024-05-29 11:15:34
 */
@Slf4j
@DS("crm")
@Service
public class WechatFollowCustomerServiceImpl extends ServiceImpl<WechatFollowCustomerMapper, WechatFollowCustomer>
        implements WechatFollowCustomerService {

    @Autowired
    private WechatFollowCustomerMapper wechatFollowCustomerMapper;
    @Autowired
    private WechatInfoService wechatInfoService;
    @Autowired
    private WechatUserSysService wechatUserSysService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    @Lazy
    private QyWxService qyWxService;
    @Autowired
    private CustomerInfoService customerInfoService;
    @Autowired
    private WechatFollowLogService wechatFollowLogService;
    @Autowired
    private WechatTagInfoService wechatTagInfoService;
    @Autowired
    private AdminUserTeamShipService adminUserTeamShipService;
    @Autowired
    private AdminTeamService teamService;
    @Autowired
    private CustomerInfoDetailService customerInfoDetailService;


    @Override
    public Map<String, String> refreshWechatCoustomerList(Long userId) {
        //查询该用户下的所有团队
        List<AdminTeam> adminTeams = wechatInfoService.teamListQuery(userId);
        if (ObjectUtils.isEmpty(adminTeams)) {
            throw new BusinessException("该用户未绑定团队");
        }
        Map<String, String> resultmap = new HashMap<>();
        //循环查询该团队关联的企业微信账号
        for (AdminTeam adminTeam : adminTeams) {
            if (!ObjectUtils.isEmpty(adminTeam.getWechatInfoId())) {
                //获取该企业名下的所有客户标签
                getAllTags(adminTeam);
                //查看该用户在该团队下的企业微信用户id
                LambdaQueryWrapper<WechatUserSys> userSysLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userSysLambdaQueryWrapper.eq(WechatUserSys::getSysUserId, userId)
                        .eq(WechatUserSys::getWechatInfoId, adminTeam.getWechatInfoId());
                WechatUserSys wechatUserSys = wechatUserSysService.getOne(userSysLambdaQueryWrapper);
                //若没有企业微信id通过用户手机好获取
                if (ObjectUtils.isEmpty(wechatUserSys)) {
                    LambdaQueryWrapper<AdminUserTeamShip> teamShipLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    teamShipLambdaQueryWrapper.eq(AdminUserTeamShip::getUserMerchantId, userId).eq(AdminUserTeamShip::getTeamId, adminTeam.getId());
                    AdminUserTeamShip teamShip = adminUserTeamShipService.getOne(teamShipLambdaQueryWrapper);
                    if (ObjectUtils.isEmpty(teamShip.getWhechatAccount())) {
                        throw new BusinessException("请先设置微信账号");
                    }
                    //String wechatUserId = qyWxService.getWechatUserByPhone(teamShip.getWhechatAccount(), adminTeam.getCorpid());
                    boolean userByUserId = qyWxService.getUserByUserId(adminTeam.getCorpid(), teamShip.getWhechatAccount());
                    if (userByUserId) {
                        wechatUserSys = new WechatUserSys();
                        wechatUserSys.setTeamId(adminTeam.getId());
                        wechatUserSys.setWechatUserId(teamShip.getWhechatAccount());
                        wechatUserSys.setWechatInfoId(adminTeam.getWechatInfoId());
                        wechatUserSys.setCorpid(adminTeam.getCorpid());
                        wechatUserSys.setSysUserId(userId.intValue());
                        wechatUserSysService.save(wechatUserSys);
                    } else {
                        resultmap.put(adminTeam.getTeamName(), ":该团队企微账号错误");
                        continue;
                    }
                }
                //批量获取客户
                GetWechatCustomersDto getWechatCustomersDto = new GetWechatCustomersDto();
                getWechatCustomersDto.setLimit(100);
                List<String> userid_list = new ArrayList<>();
                userid_list.add(wechatUserSys.getWechatUserId());
                getWechatCustomersDto.setUserid_list(userid_list);
                WechatFollowCustomerListVo wechatCustomers = qyWxService.getWechatCustomers(adminTeam.getCorpid(), getWechatCustomersDto);
                if (!ObjectUtils.isEmpty(wechatCustomers)) {
                    List<WechatFollowCustomer> wechatFollowCustomerList = wechatCustomers.getWechatFollowCustomerList();
                    //判断是否重复的用户 并修改或保存用户
                    judgeFollowCustomer(wechatFollowCustomerList, wechatUserSys);
                    //判断next_cursor是否为空 不为空继续请求
                    while (!ObjectUtils.isEmpty(wechatCustomers.getNext_cursor())) {
                        getWechatCustomersDto.setCursor(wechatCustomers.getNext_cursor());
                        wechatCustomers = qyWxService.getWechatCustomers(adminTeam.getCorpid(), getWechatCustomersDto);
                        wechatFollowCustomerList = wechatCustomers.getWechatFollowCustomerList();
                        //判断是否重复的用户 并修改或保存用户
                        judgeFollowCustomer(wechatFollowCustomerList, wechatUserSys);
                    }
                }
            } else {
                resultmap.put(adminTeam.getTeamName(), "该团队未关联企业微信");
            }
        }
        return resultmap;
    }


    @Override
    public void refWectCoustomerById(Long userId, Long followCustomer) {
        WechatFollowCustomer agoFollowCustomer = this.getById(followCustomer);
        if (ObjectUtils.isEmpty(agoFollowCustomer)) {
            throw new BusinessException("未找到资源");
        }
        WechatInfo wechatInfo = wechatInfoService.getById(agoFollowCustomer.getWechatInfoId());
        WechatFollowCustomer wechatCustomer = qyWxService.getWechatCustomer(wechatInfo.getCorpid(), agoFollowCustomer.getExternalUserid(), agoFollowCustomer.getWechatUserId());
        if (!ObjectUtils.isEmpty(wechatCustomer)) {
            LambdaQueryWrapper<WechatUserSys> wechatUserSysLambdaQueryWrapper = new LambdaQueryWrapper<>();
            wechatUserSysLambdaQueryWrapper.eq(WechatUserSys::getSysUserId, userId)
                    .eq(WechatUserSys::getTeamId, agoFollowCustomer.getTeamId());
            WechatUserSys wechatUserSys = wechatUserSysService.getOne(wechatUserSysLambdaQueryWrapper);
            refWectCoustomer(wechatCustomer,wechatUserSys);
//            wechatCustomer.setId(agoFollowCustomer.getId());
//            wechatCustomer.setCustomerNo("-1");
//            wechatCustomer.setTeamId(agoFollowCustomer.getTeamId());
//            wechatCustomer.setSysUserId(agoFollowCustomer.getSysUserId());
//            wechatCustomer.setWechatInfoId(agoFollowCustomer.getWechatInfoId());
//            //解除之前绑定系统客户关系
//            if (!ObjectUtils.isEmpty(agoFollowCustomer.getCustomerNo()) && !agoFollowCustomer.getCustomerNo().equals("-1")) {
//                LambdaQueryWrapper<CustomerInfo> customerInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                customerInfoLambdaQueryWrapper.eq(CustomerInfo::getCustomerNo, agoFollowCustomer.getCustomerNo());
//                CustomerInfo agoCustomerInfo = customerInfoService.getOne(customerInfoLambdaQueryWrapper);
//                if (!ObjectUtils.isEmpty(agoCustomerInfo)) {
//                    agoCustomerInfo.setIsWechat(0);
//                    agoCustomerInfo.setSalesmanId(-1);
//                    if (agoCustomerInfo.getTelephonerId()==-1){
//                        agoCustomerInfo.setTeamId(-1);
//                    }
//                    List<Long> unParsedList = null;
//                    String unWechatFollowIdsObject = (String) agoCustomerInfo.getUnWechatFollowIds();
//                    if (!ObjectUtils.isEmpty(unWechatFollowIdsObject) && !unWechatFollowIdsObject.equals("[null]") && JSON.parseArray(unWechatFollowIdsObject, Long.class).size() > 0) {
//                        unParsedList = JSON.parseArray(unWechatFollowIdsObject, Long.class);
//                        if (!unParsedList.contains(wechatCustomer.getId())) {
//                            unParsedList.add(wechatCustomer.getId());
//                        }
//                    } else {
//                        unParsedList = new ArrayList<>();
//                        unParsedList.add(wechatCustomer.getId());
//                    }
//                    agoCustomerInfo.setUnWechatFollowIds(JSON.toJSONString(unParsedList));
//                    LambdaQueryWrapper<WechatFollowLog> wechatFollowLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    wechatFollowLogLambdaQueryWrapper.eq(WechatFollowLog::getWechatFollowId, agoFollowCustomer.getId())
//                            .eq(WechatFollowLog::getCustomerInfoId, agoCustomerInfo.getId())
//                            .eq(WechatFollowLog::getType, 2);
//                    long count = wechatFollowLogService.count(wechatFollowLogLambdaQueryWrapper);
//                    if (count < 1) {
//                        WechatFollowLog wechatFollowLog = new WechatFollowLog();
//                        wechatFollowLog.setCustomerInfoId(agoCustomerInfo.getId());
//                        wechatFollowLog.setWechatFollowId(agoFollowCustomer.getId());
//                        wechatFollowLog.setType(2);
//                        wechatFollowLogService.save(wechatFollowLog);
//                    }
//                    customerInfoService.updateById(agoCustomerInfo);
//                }
//            }
//            //绑定新的系统客户关系
//            Object wechatRemarkMobiles = wechatCustomer.getWechatRemarkMobiles();
//            List<String> mobiles = JSON.parseArray(wechatRemarkMobiles.toString(), String.class);
//            if (mobiles.size() > 0) {
//                LambdaQueryWrapper<CustomerInfo> customerInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                customerInfoLambdaQueryWrapper.in(CustomerInfo::getPhone, mobiles)
//                        .eq(CustomerInfo::getSalesmanId, wechatCustomer.getSysUserId())
//                        .eq(CustomerInfo::getTeamId, agoFollowCustomer.getTeamId())
//                        .ne(CustomerInfo::getIsWechat, 1);
//                List<CustomerInfo> customerInfoList = customerInfoService.list(customerInfoLambdaQueryWrapper);
//                if (!ObjectUtils.isEmpty(customerInfoList) && customerInfoList.size() > 0) {
//                    CustomerInfo newCustomerInfo = customerInfoList.get(0);
//                    wechatCustomer.setCustomerNo(newCustomerInfo.getCustomerNo());
//                    newCustomerInfo.setIsWechat(1);
//                    List<Long> parsedList = null;
//                    String wechatFollowIds = (String) newCustomerInfo.getWechatFollowIds();
//                    if (!ObjectUtils.isEmpty(wechatFollowIds) && !wechatFollowIds.equals("[null]") && JSON.parseArray(wechatFollowIds, Long.class).size() > 0) {
//                        parsedList = JSON.parseArray(wechatFollowIds, Long.class);
//                        if (!parsedList.contains(wechatCustomer.getId())) {
//                            parsedList.add(wechatCustomer.getId());
//                        }
//                    } else {
//                        parsedList = new ArrayList<>();
//                        parsedList.add(wechatCustomer.getId());
//                    }
//                    newCustomerInfo.setWechatFollowIds(JSON.toJSONString(parsedList));
//                    customerInfoService.updateById(newCustomerInfo);
//                    //保存日志
//                    LambdaQueryWrapper<WechatFollowLog> wechatFollowLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    wechatFollowLogLambdaQueryWrapper.eq(WechatFollowLog::getWechatFollowId, wechatCustomer.getId())
//                            .eq(WechatFollowLog::getCustomerInfoId, newCustomerInfo.getId())
//                            .eq(WechatFollowLog::getType, 1);
//                    long count = wechatFollowLogService.count(wechatFollowLogLambdaQueryWrapper);
//                    if (count < 1) {
//                        WechatFollowLog wechatFollowLog = new WechatFollowLog();
//                        wechatFollowLog.setCustomerInfoId(newCustomerInfo.getId());
//                        wechatFollowLog.setWechatFollowId(wechatCustomer.getId());
//                        wechatFollowLog.setType(1);
//                        wechatFollowLogService.save(wechatFollowLog);
//                    }
//                }
//            }
//            this.updateById(wechatCustomer);
        } else {
            if (agoFollowCustomer.getRunType() == 0) {
                agoFollowCustomer.setRunType(3);
                agoFollowCustomer.setRunTime(new Date().getTime() / 1000);
                //followCustomer.setAddStatus(0);
                this.updateById(agoFollowCustomer);
            }
        }
    }

    @Override
    public void refWectCoustomer(WechatFollowCustomer wechatCustomer, WechatUserSys wechatUserSys) {
        if (!ObjectUtils.isEmpty(wechatCustomer)) {
            wechatCustomer.setTeamId(wechatUserSys.getTeamId());
            wechatCustomer.setWechatInfoId(wechatUserSys.getWechatInfoId());
            wechatCustomer.setSysUserId(wechatUserSys.getSysUserId());
            LambdaQueryWrapper<WechatFollowCustomer> wechatFollowCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
            wechatFollowCustomerLambdaQueryWrapper.eq(WechatFollowCustomer::getExternalUserid, wechatCustomer.getExternalUserid())
                    .eq(WechatFollowCustomer::getWechatUserId, wechatUserSys.getWechatUserId())
                    .eq(WechatFollowCustomer::getWechatInfoId, wechatUserSys.getWechatInfoId());
            WechatFollowCustomer agoFollowCustomer = this.getOne(wechatFollowCustomerLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(agoFollowCustomer)) {
                wechatCustomer.setId(agoFollowCustomer.getId());
                wechatCustomer.setCustomerNo("-1");
                if (!ObjectUtils.isEmpty(agoFollowCustomer.getCustomerNo()) && !agoFollowCustomer.getCustomerNo().equals("-1")) {
                    //解除绑定
                    LambdaQueryWrapper<CustomerInfo> customerInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    customerInfoLambdaQueryWrapper.eq(CustomerInfo::getCustomerNo, agoFollowCustomer.getCustomerNo());
                    CustomerInfo agoCustomerInfo = customerInfoService.getOne(customerInfoLambdaQueryWrapper);
                    if (!ObjectUtils.isEmpty(agoCustomerInfo)) {
                        agoCustomerInfo.setIsWechat(0);
                        agoCustomerInfo.setSalesmanId(-1);
                        if (agoCustomerInfo.getTelephonerId()==-1){
                            agoCustomerInfo.setTeamId(-1);
                        }
                        List<Long> unParsedList = null;
                        String unWechatFollowIdsObject = (String) agoCustomerInfo.getUnWechatFollowIds();
                        if (!ObjectUtils.isEmpty(unWechatFollowIdsObject) && !unWechatFollowIdsObject.equals("[null]") && JSON.parseArray(unWechatFollowIdsObject, Long.class).size() > 0) {
                            unParsedList = JSON.parseArray(unWechatFollowIdsObject, Long.class);
                            if (!unParsedList.contains(wechatCustomer.getId())) {
                                unParsedList.add(wechatCustomer.getId());
                            }
                        } else {
                            unParsedList = new ArrayList<>();
                            unParsedList.add(wechatCustomer.getId());
                        }
                        agoCustomerInfo.setUnWechatFollowIds(JSON.toJSONString(unParsedList));
                        LambdaQueryWrapper<WechatFollowLog> wechatFollowLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        wechatFollowLogLambdaQueryWrapper.eq(WechatFollowLog::getWechatFollowId, wechatCustomer.getId())
                                .eq(WechatFollowLog::getCustomerInfoId, agoCustomerInfo.getId())
                                .eq(WechatFollowLog::getType, 2);
                        long count = wechatFollowLogService.count(wechatFollowLogLambdaQueryWrapper);
                        if (count < 1) {
                            WechatFollowLog wechatFollowLog = new WechatFollowLog();
                            wechatFollowLog.setCustomerInfoId(agoCustomerInfo.getId());
                            wechatFollowLog.setWechatFollowId(wechatCustomer.getId());
                            wechatFollowLog.setType(2);
                            wechatFollowLogService.save(wechatFollowLog);
                        }
                        customerInfoService.updateById(agoCustomerInfo);
                    }
                }
            }
            //绑定新的客户关系
            Object wechatRemarkMobiles = wechatCustomer.getWechatRemarkMobiles();
            List<String> mobiles = JSON.parseArray(wechatRemarkMobiles.toString(), String.class);
            CustomerInfo newCustomerInfo = null;
            if (mobiles.size() > 0) {
                //通过团队id获取商户id
                AdminTeam team = teamService.getByTeamId(wechatUserSys.getTeamId());
                LambdaQueryWrapper<CustomerInfo> customerInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                customerInfoLambdaQueryWrapper.in(CustomerInfo::getPhone, mobiles)
                        .eq(CustomerInfo::getMerchantId,team.getMerchantId())
                        .and(i->i.eq(CustomerInfo::getSalesmanId,-1).or().eq(CustomerInfo::getSalesmanId, wechatUserSys.getSysUserId()))
                        .and(i->i.eq(CustomerInfo::getTeamId, -1).or().eq(CustomerInfo::getTeamId,wechatUserSys.getTeamId()))
                        .ne(CustomerInfo::getIsWechat, 1);
                List<CustomerInfo> customerInfoList = customerInfoService.list(customerInfoLambdaQueryWrapper);

                if (!customerInfoList.isEmpty()) {
                    //绑定业务员和团队
                    newCustomerInfo = customerInfoList.get(0);
                    wechatCustomer.setCustomerNo(newCustomerInfo.getCustomerNo());
                    newCustomerInfo.setIsWechat(1);
                    newCustomerInfo.setTeamId(wechatUserSys.getTeamId());
                    newCustomerInfo.setSalesmanId(wechatUserSys.getSysUserId());
                    newCustomerInfo.setSalesmanTime(new Date());
                    newCustomerInfo.setSeasType(0);
                    List<Long> parsedList = null;
                    String wechatFollowIds = (String) newCustomerInfo.getWechatFollowIds();
                    if (!ObjectUtils.isEmpty(wechatFollowIds) && !wechatFollowIds.equals("[null]") && JSON.parseArray(wechatFollowIds, Long.class).size() > 0) {
                        parsedList = JSON.parseArray(wechatFollowIds, Long.class);
                        if (!parsedList.contains(wechatCustomer.getId())) {
                            parsedList.add(wechatCustomer.getId());
                        }
                    } else {
                        parsedList = new ArrayList<>();
                        parsedList.add(wechatCustomer.getId());
                    }
                    newCustomerInfo.setWechatFollowIds(JSON.toJSONString(parsedList));
                    customerInfoService.updateById(newCustomerInfo);
                }
            }
            this.saveOrUpdate(wechatCustomer);
            //保存日志
            if (!ObjectUtils.isEmpty(newCustomerInfo)) {
                LambdaQueryWrapper<WechatFollowLog> wechatFollowLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
                wechatFollowLogLambdaQueryWrapper.eq(WechatFollowLog::getWechatFollowId, wechatCustomer.getId())
                        .eq(WechatFollowLog::getCustomerInfoId, newCustomerInfo.getId())
                        .eq(WechatFollowLog::getType, 1);
                long count = wechatFollowLogService.count(wechatFollowLogLambdaQueryWrapper);
                if (count < 1) {
                    WechatFollowLog wechatFollowLog = new WechatFollowLog();
                    wechatFollowLog.setCustomerInfoId(newCustomerInfo.getId());
                    wechatFollowLog.setWechatFollowId(wechatCustomer.getId());
                    wechatFollowLog.setType(1);
                    wechatFollowLogService.save(wechatFollowLog);
                }
            }
        }
    }

    @Override
    public void refRunCoustomer(WechatUserSys wechatUserSys, String externalUserid, Integer runType, Long runTime, String source) {
        LambdaQueryWrapper<WechatFollowCustomer> wechatFollowCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        wechatFollowCustomerLambdaQueryWrapper.eq(WechatFollowCustomer::getExternalUserid, externalUserid)
                .eq(WechatFollowCustomer::getWechatUserId, wechatUserSys.getWechatUserId())
                .eq(WechatFollowCustomer::getWechatInfoId, wechatUserSys.getWechatInfoId());
        WechatFollowCustomer agoFollowCustomer = this.getOne(wechatFollowCustomerLambdaQueryWrapper);
        if (!ObjectUtils.isEmpty(agoFollowCustomer)) {
            agoFollowCustomer.setRunType(runType);
            agoFollowCustomer.setRunTime(runTime);
            agoFollowCustomer.setRunSource(source);
            //agoFollowCustomer.setAddStatus(0);
            this.updateById(agoFollowCustomer);
        }
    }

    @Override
    public IPage<CustomerWechatInfoVo> customerWechatPageQuery(Page<CustomerWechatInfoVo> page, CustomerWechatPageDto command) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            if (!ObjectUtils.isEmpty(command.getStartWechatAddTime())) {
                Date startWechatAddDate = sdf.parse(command.getStartWechatAddTime());
                command.setStartWechatAddTimeLong(startWechatAddDate.getTime() / 1000);
            }
            if (!ObjectUtils.isEmpty(command.getEndWechatAddTime())) {
                Date endWechatAddDate = sdf.parse(command.getEndWechatAddTime());
                command.setEndWechatAddTimeLong(endWechatAddDate.getTime() / 1000);
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        IPage<CustomerWechatInfoVo> customerWechatInfoVoIPage = wechatFollowCustomerMapper.customerWechatPageQuery(page, command);
        List<CustomerWechatInfoVo> records = customerWechatInfoVoIPage.getRecords();
        if (!ObjectUtils.isEmpty(records) && records.size() > 0) {
            Set<Integer> teamIds = new HashSet<>();
            Set<Integer> userIds = new HashSet<>();
            Set<Long> wechatInfoIds = new HashSet<>();
            Set<Integer> customerIds=new HashSet<>();
            for (CustomerWechatInfoVo record : records) {
                wechatInfoIds.add(record.getWechatInfoId());
                if (!ObjectUtils.isEmpty(record.getTeamId())) {
                    teamIds.add(record.getTeamId());
                }
                if (!ObjectUtils.isEmpty(record.getSalesmanId())) {
                    userIds.add(record.getSalesmanId());
                }
                if (!ObjectUtils.isEmpty(record.getTelephonerId())) {
                    userIds.add(record.getTelephonerId());
                }
                if (!ObjectUtils.isEmpty(record.getCustomerId())) {
                    customerIds.add(record.getCustomerId());
                }
            }
            //团队名
            Map<Integer, String> teamMap = new HashMap<>();
            if (!teamIds.isEmpty()) {
                List<AdminTeam> teams = teamService.listByIds(teamIds);
                teamMap = teams.stream().collect(Collectors.toMap(AdminTeam::getId, AdminTeam::getTeamName));
            }
            //业务话务名
            Map<Integer, String> userMap = new HashMap<>();
            if (!userIds.isEmpty()) {
                List<AdminUser> adminUsers = adminUserService.listByIds(userIds);
                userMap = adminUsers.stream().collect(Collectors.toMap(AdminUser::getId, AdminUser::getNickname));
            }
            //企微名字
            List<WechatInfo> wechatInfos = wechatInfoService.listByIds(wechatInfoIds);
            Map<Long, String> wechatInfoMap = wechatInfos.stream().collect(Collectors.toMap(WechatInfo::getId, WechatInfo::getCorpName));
            //客户详情
            Map<Long, CustomerInfoDetail> customerInfoDetailMap = new HashMap<>();
            if (!customerIds.isEmpty()){
                LambdaQueryWrapper<CustomerInfoDetail> infoDetailLambdaQueryWrapper=new LambdaQueryWrapper<>();
                infoDetailLambdaQueryWrapper.in(CustomerInfoDetail::getCustomerInfoId,customerIds);
                List<CustomerInfoDetail> customerInfoDetails = customerInfoDetailService.list(infoDetailLambdaQueryWrapper);
                customerInfoDetailMap = customerInfoDetails.stream().collect(Collectors.toMap(CustomerInfoDetail::getCustomerInfoId, obj -> obj));
            }

            for (CustomerWechatInfoVo record : records) {
                record.setCorpName(wechatInfoMap.get(record.getWechatInfoId()));
                if (!ObjectUtils.isEmpty(record.getTeamId()) && record.getTeamId() != -1) {
                    record.setTeamName(teamMap.get(record.getTeamId()));
                }
                if (!ObjectUtils.isEmpty(record.getSalesmanId()) && record.getSalesmanId() != -1) {
                    record.setSalesmanName(userMap.get(record.getSalesmanId()));
                }
                if (!ObjectUtils.isEmpty(record.getTelephonerId()) && record.getTelephonerId() != -1) {
                    record.setTelephonerName(userMap.get(record.getTelephonerId()));
                }
                if (!ObjectUtils.isEmpty(record.getCustomerId()) && record.getCustomerId() != -1) {
                    record.setCustomerInfoDetail(customerInfoDetailMap.get(record.getCustomerId().longValue()));
                }
            }
        }
        return customerWechatInfoVoIPage;
    }

    @Override
    public String listWechatCustomerTag(Long wechatCustomerId) {
        return wechatFollowCustomerMapper.listWechatCustomerTag(wechatCustomerId);
    }

    //刷新客户
    private void judgeFollowCustomer(List<WechatFollowCustomer> wechatFollowCustomerList, WechatUserSys wechatUserSys) {
        if (!ObjectUtils.isEmpty(wechatFollowCustomerList)) {
            List<String> followCustomerIds = wechatFollowCustomerList.stream().map(i -> i.getExternalUserid()).toList();
            LambdaQueryWrapper<WechatFollowCustomer> followCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
            followCustomerLambdaQueryWrapper.select(WechatFollowCustomer::getId, WechatFollowCustomer::getCustomerNo, WechatFollowCustomer::getExternalUserid)
                    .in(WechatFollowCustomer::getExternalUserid, followCustomerIds)
                    .eq(WechatFollowCustomer::getWechatUserId, wechatUserSys.getWechatUserId());
            List<WechatFollowCustomer> wechatFollowCustomers = this.list(followCustomerLambdaQueryWrapper);
            Map<String, WechatFollowCustomer> wechatFollowCustomerMap = new HashMap<>();
            if (!ObjectUtils.isEmpty(wechatFollowCustomers)) {
                List<String> agoCustomrNos = new ArrayList<>();
                Map<String, Long> agoCustomerNoMap = new HashMap<>();
                for (WechatFollowCustomer wechatFollowCustomer : wechatFollowCustomers) {
                    wechatFollowCustomerMap.put(wechatFollowCustomer.getExternalUserid(), wechatFollowCustomer);
                    if (!ObjectUtils.isEmpty(wechatFollowCustomer.getCustomerNo()) && !wechatFollowCustomer.getCustomerNo().equals("-1")) {
                        agoCustomrNos.add(wechatFollowCustomer.getCustomerNo());
                        agoCustomerNoMap.put(wechatFollowCustomer.getCustomerNo(),wechatFollowCustomer.getId());
                    }
                }
                //取消之前绑定
                if (!ObjectUtils.isEmpty(agoCustomrNos) && agoCustomrNos.size() > 0) {
                    LambdaQueryWrapper<CustomerInfo> customerInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    customerInfoLambdaQueryWrapper.in(CustomerInfo::getCustomerNo, agoCustomrNos);
                    List<CustomerInfo> agoCustomerInfos = customerInfoService.list(customerInfoLambdaQueryWrapper);
                    List<WechatFollowLog> unFollowLogs = new ArrayList<>();
                    boolean unflag = false;
                    for (CustomerInfo agoCustomerInfo : agoCustomerInfos) {
                        Long unFollowId = agoCustomerNoMap.get(agoCustomerInfo.getCustomerNo());
                        agoCustomerInfo.setIsWechat(0);
                        agoCustomerInfo.setSalesmanId(-1);
                        if (agoCustomerInfo.getTelephonerId()==-1){
                            agoCustomerInfo.setTeamId(-1);
                        }
                        List<Long> unParsedList = null;
                        String unWechatFollowIdsObject = (String) agoCustomerInfo.getUnWechatFollowIds();
                        if (!ObjectUtils.isEmpty(unWechatFollowIdsObject) && !unWechatFollowIdsObject.equals("[null]") && JSON.parseArray(unWechatFollowIdsObject, Long.class).size() > 0) {
                            unParsedList = JSON.parseArray(unWechatFollowIdsObject, Long.class);
                            if (!unParsedList.contains(unFollowId)) {
                                unParsedList.add(unFollowId);
                            }
                        } else {
                            unParsedList = new ArrayList<>();
                            unParsedList.add(unFollowId);
                        }
                        agoCustomerInfo.setUnWechatFollowIds(JSON.toJSONString(unParsedList));
                        LambdaQueryWrapper<WechatFollowLog> wechatFollowLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        wechatFollowLogLambdaQueryWrapper.eq(WechatFollowLog::getWechatFollowId, unFollowId)
                                .eq(WechatFollowLog::getCustomerInfoId, agoCustomerInfo.getId())
                                .eq(WechatFollowLog::getType, 2);
                        long count = wechatFollowLogService.count(wechatFollowLogLambdaQueryWrapper);
                        if (count < 1) {
                            WechatFollowLog wechatFollowLog = new WechatFollowLog();
                            wechatFollowLog.setCustomerInfoId(agoCustomerInfo.getId());
                            wechatFollowLog.setWechatFollowId(unFollowId);
                            wechatFollowLog.setType(2);
                            unFollowLogs.add(wechatFollowLog);
                        }
                        unflag = true;
                    }
                    if (unflag) {
                        customerInfoService.updateBatchById(agoCustomerInfos);
                        if (unFollowLogs.size() > 0) {
                            wechatFollowLogService.saveBatch(unFollowLogs);
                        }
                    }
                }
            }

            //绑定系统客户
            Set<String> mobileSet = new HashSet<>();
            for (WechatFollowCustomer wechatFollowCustomer : wechatFollowCustomerList) {
                Object wechatRemarkMobiles = wechatFollowCustomer.getWechatRemarkMobiles();
                if (!ObjectUtils.isEmpty(wechatRemarkMobiles)) {
                    List<String> mobiles = JSON.parseArray(wechatRemarkMobiles.toString(), String.class);
                    if (mobiles.size() > 0) {
                        mobileSet.addAll(mobiles);
                    }
                }
                WechatFollowCustomer agoFollowCustomer = wechatFollowCustomerMap.get(wechatFollowCustomer.getExternalUserid());
                if (!ObjectUtils.isEmpty(agoFollowCustomer)) {
                    wechatFollowCustomer.setId(agoFollowCustomer.getId());
                    wechatFollowCustomer.setCustomerNo("-1");
                }
                wechatFollowCustomer.setSysUserId(wechatUserSys.getSysUserId());
                wechatFollowCustomer.setWechatInfoId(wechatUserSys.getWechatInfoId());
                wechatFollowCustomer.setTeamId(wechatUserSys.getTeamId());
            }

            if (!ObjectUtils.isEmpty(mobileSet)) {
                AdminTeam team = teamService.getByTeamId(wechatUserSys.getTeamId());
                LambdaQueryWrapper<CustomerInfo> customerInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                customerInfoLambdaQueryWrapper.eq(CustomerInfo::getMerchantId,team.getMerchantId())
                        .and(i->i.eq(CustomerInfo::getSalesmanId, -1).or().eq(CustomerInfo::getSalesmanId, wechatUserSys.getSysUserId()))
                        .and(i->i.eq(CustomerInfo::getTeamId,-1).or().eq(CustomerInfo::getTeamId,wechatUserSys.getTeamId()))
                        .in(CustomerInfo::getPhone, mobileSet)
                        .ne(CustomerInfo::getIsWechat, 1);
                List<CustomerInfo> newCustomerInfoList = customerInfoService.list(customerInfoLambdaQueryWrapper);
                Map<String, CustomerInfo> newCustomerInfoMaps = newCustomerInfoList.stream().collect(Collectors.toMap(
                        CustomerInfo::getPhone, Function.identity(),
                        (existing, replacement) -> existing,
                        LinkedHashMap::new
                        ));

                for (WechatFollowCustomer wechatFollowCustomer : wechatFollowCustomerList) {
                    Object wechatRemarkMobiles = wechatFollowCustomer.getWechatRemarkMobiles();
                    if (!ObjectUtils.isEmpty(wechatRemarkMobiles)) {
                        List<String> mobiles = JSON.parseArray(wechatRemarkMobiles.toString(), String.class);
                        CustomerInfo newCustomerInfo = null;
                        for (String mobile : mobiles) {
                            newCustomerInfo = newCustomerInfoMaps.get(mobile);

                            if (!ObjectUtils.isEmpty(newCustomerInfo) && newCustomerInfo.getIsWechat()!=1) {
                                wechatFollowCustomer.setCustomerNo(newCustomerInfo.getCustomerNo());
                                newCustomerInfo.setIsWechat(1);
                                newCustomerInfo.setTeamId(wechatUserSys.getTeamId());
                                newCustomerInfo.setSalesmanId(wechatUserSys.getSysUserId());
                                newCustomerInfo.setSalesmanTime(new Date());
                                newCustomerInfo.setSeasType(0);
                                List<Long> parsedList = null;
                                String wechatFollowIdsObject = (String) newCustomerInfo.getWechatFollowIds();
                                if (!ObjectUtils.isEmpty(wechatFollowIdsObject) && !wechatFollowIdsObject.equals("[null]") && JSON.parseArray(wechatFollowIdsObject, Long.class).size() > 0) {
                                    parsedList = JSON.parseArray(wechatFollowIdsObject, Long.class);
                                    if (!parsedList.contains(wechatFollowCustomer.getId())) {
                                        parsedList.add(wechatFollowCustomer.getId());
                                    }
                                } else {
                                    parsedList = new ArrayList<>();
                                    parsedList.add(wechatFollowCustomer.getId());
                                }
                                newCustomerInfo.setWechatFollowIds(JSON.toJSONString(parsedList));
                                break;
                            }
                        }
                    }
                }
                this.saveOrUpdateBatch(wechatFollowCustomerList);
                if (!ObjectUtils.isEmpty(newCustomerInfoList)) {
                    customerInfoService.updateBatchById(newCustomerInfoList);
                    //保存日志
                    Map<String, CustomerInfo> CustomerNoName = newCustomerInfoList.stream().collect(Collectors.toMap(CustomerInfo::getCustomerNo, obj -> obj));
                    List<WechatFollowLog> followLogs = new ArrayList<>();
                    for (WechatFollowCustomer wechatFollowCustomer : wechatFollowCustomerList) {
                        if (!ObjectUtils.isEmpty(wechatFollowCustomer.getCustomerNo()) && !wechatFollowCustomer.getCustomerNo().equals("-1")) {
                            CustomerInfo customerInfo = CustomerNoName.get(wechatFollowCustomer.getCustomerNo());
                            LambdaQueryWrapper<WechatFollowLog> wechatFollowLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            wechatFollowLogLambdaQueryWrapper.eq(WechatFollowLog::getWechatFollowId, wechatFollowCustomer.getId())
                                    .eq(WechatFollowLog::getCustomerInfoId, customerInfo.getId())
                                    .eq(WechatFollowLog::getType, 1);
                            long count = wechatFollowLogService.count(wechatFollowLogLambdaQueryWrapper);
                            if (count < 1) {
                                WechatFollowLog wechatFollowLog = new WechatFollowLog();
                                wechatFollowLog.setCustomerInfoId(customerInfo.getId());
                                wechatFollowLog.setWechatFollowId(wechatFollowCustomer.getId());
                                wechatFollowLog.setType(1);
                                followLogs.add(wechatFollowLog);
                            }
                        }
                    }
                    if (followLogs.size() > 0) {
                        wechatFollowLogService.saveBatch(followLogs);
                    }
                }

            }
        }
    }

    private void getAllTags(AdminTeam adminTeam) {
        //获取该企业名下的所有客户标签
        List<WechatGroupTagVo> wechatGroupTagVoList = qyWxService.getWechatTags(adminTeam.getCorpid());
        if (!ObjectUtils.isEmpty(wechatGroupTagVoList)) {
            List<WechatTagInfo> wechatTagInfoList = new ArrayList<>();
            for (WechatGroupTagVo wechatGroupTagVo : wechatGroupTagVoList) {
                WechatTagInfo wechatGroupTagInfo = new WechatTagInfo();
                wechatGroupTagInfo.setWechatInfoId(adminTeam.getWechatInfoId());
                wechatGroupTagInfo.setWechatGroupId("0");
                wechatGroupTagInfo.setTreePath("0");
                wechatGroupTagInfo.setTagId(wechatGroupTagVo.getGroup_id());
                wechatGroupTagInfo.setLevel(1);
                wechatGroupTagInfo.setTagName(wechatGroupTagVo.getGroup_name());
                wechatGroupTagInfo.setType(1);
                wechatGroupTagInfo.setWechatCreateTime(wechatGroupTagVo.getCreate_time());
                wechatTagInfoList.add(wechatGroupTagInfo);
                List<WechatGroupTagVo.WechatTagVo> tags = wechatGroupTagVo.getTags();
                for (WechatGroupTagVo.WechatTagVo tag : tags) {
                    WechatTagInfo wechatTagInfo = new WechatTagInfo();
                    wechatTagInfo.setWechatInfoId(adminTeam.getWechatInfoId());
                    wechatTagInfo.setWechatGroupId(wechatGroupTagInfo.getTagId());
                    wechatTagInfo.setTreePath("0," + wechatGroupTagInfo.getTagId());
                    wechatTagInfo.setTagId(tag.getId());
                    wechatTagInfo.setLevel(2);
                    wechatTagInfo.setTagName(tag.getName());
                    wechatTagInfo.setType(2);
                    wechatTagInfo.setWechatCreateTime(tag.getCreate_time());
                    wechatTagInfo.setWechatOrder(tag.getOrder());
                    wechatTagInfoList.add(wechatTagInfo);
                }
            }
            List<String> tagIdlist = wechatTagInfoList.stream().map(i -> i.getTagId()).toList();
            LambdaQueryWrapper<WechatTagInfo> wechatTagInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            wechatTagInfoLambdaQueryWrapper.select(WechatTagInfo::getId, WechatTagInfo::getTagId)
                    .eq(WechatTagInfo::getWechatInfoId, adminTeam.getWechatInfoId())
                    .in(WechatTagInfo::getTagId, tagIdlist);
            List<WechatTagInfo> agoTags = wechatTagInfoService.list(wechatTagInfoLambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(agoTags)) {
                List<String> agoTagIds = agoTags.stream().map(i -> i.getTagId()).toList();
                Map<String, Long> collect = agoTags.stream().collect(Collectors.toMap(obj -> obj.getTagId(), obj -> obj.getId()));
                for (WechatTagInfo wechatTagInfo : wechatTagInfoList) {
                    if (agoTagIds.contains(wechatTagInfo.getTagId())) {
                        Long id = collect.get(wechatTagInfo.getTagId());
                        wechatTagInfo.setId(id);
                    }
                }
            }
            wechatTagInfoService.saveOrUpdateBatch(wechatTagInfoList);
        }
    }
}




